package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 工种&种类维护
 */
@RestController
@RequestMapping("/system/workClass")
public class WorkClassAndTypeController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${webSystemIP}")
    private String webSystemIP;

    @Autowired
    private Dao dao;

    @RequestMapping("/list")
    public Object workClassList() {
        try {
            String response = HttpUtil.post(webSystemIP + "/system/workClass/list", null);
            Result result = Json.fromJson(Result.class, response);
            return result;
        } catch (Exception e) {
            log.error("workClass/list: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    /**
     * 查询该项目下已经进场的所有工类工种  返回工类工种的name和工种的ID
     * @param projectId
     * @return
     */
    @RequestMapping("/getTypeByProject")
    public Object getTypeByProject(@RequestParam("projectId") String projectId) {
        try {

            Cnd cnd = Cnd.where("workman_out_date", "is", null).and("project_id", "=", projectId);
            List<Record> teamProject = dao.query("bi_re_workman_and_teamproject", cnd);
            Set<Long> types = new HashSet();
            teamProject.stream().forEach(item -> types.add(item.getLong("work_type_id")));

            List<Map> data = new ArrayList<>();
            for (Long typeId : types) {
                Map<String, Object> m = new HashMap<>();

                Record type = dao.fetch("sys_work_type", Cnd.where("id", "=", typeId));
                Record workClass = dao.fetch("sys_work_class", Cnd.where("id", "=", type.getLong("work_class_id")));

                Map<String, String> m2 = new HashMap<>();
                m2.put("typeId", typeId + "");
                m2.put("typeName", type.getString("name"));

                m.put("className", workClass.getString("name"));
                m.put("types", m2);
                data.add(m);
            }

            return Result.success(Constant.API_OPERATION_SUCCESS, data);
        } catch (Exception e) {
            log.error("workClass/getTypeByProject: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

}
